import { MessageHandler } from 'element-plus'
const hexToRgb = (str: string): Array<number> => {
  let hexs: Array<number> = []
  const reg = /^#?[0-9A-Fa-f]{6}$/
  if (!reg.test(str)) {
    ElMessage.warning('输入错误的hex')
    return []
  }
  str = str.replace('#', '')
  const hexString: Array<string> = str.match(/../g)!
  for (let i = 0; i < 3; i++) hexs[i] = parseInt(hexString[i], 16)
  return hexs
}
const rgbToHex = (r: number, g: number, b: number) => {
  const reg = /^\d{1,3}$/
  if (!reg.test(r + '') || !reg.test(g + '') || !reg.test(b + ''))
    return ElMessage.warning('输入错误的rgb颜色值')
  const hexs = [r.toString(16), g.toString(16), b.toString(16)]
  for (let i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`
  return `#${hexs.join('')}`
}

export function getLightDarkColor(
  color: string,
  level: number,
  isDark: boolean = false
): string | MessageHandler {
  const reg = /^#?[0-9A-Fa-f]{6}$/
  if (!reg.test(color)) return ElMessage.warning('输入错误的hex颜色值')
  const rgb = hexToRgb(color)!
  const x = isDark ? 20.5 : 255
  for (let i = 0; i < 3; i++) rgb[i] = Math.round(x * level + rgb[i] * (1 - level))
  return rgbToHex(rgb[0], rgb[1], rgb[2])
}
